using B.Z.BasicData.Infrastructure;
using B.Z.Inventory.API.Read.Application.Command;
using B.Z.Inventory.API.Read.DTO;
using B.Z.Inventory.Domain;
using B.Z.Inventory.ErrorCode;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.Z.Inventory.API.Read.Application.CommandHandler
{
    /// <summary>
    /// 仓库查询命令处理器
    /// </summary>
    public class StoreQueryCommandHandler : IRequestHandler<StoreQueryCommand, APIResult<APIPaging<StoreDto>>>
    {
        private readonly IBaseRepository<T_Store> storeRepository;
        private readonly ILogger<StoreQueryCommandHandler> logger;

        public StoreQueryCommandHandler(IBaseRepository<T_Store> storeRepository, ILogger<StoreQueryCommandHandler> logger)
        {
            this.storeRepository = storeRepository;
            this.logger = logger;
        }

        public Task<APIResult<APIPaging<StoreDto>>> Handle(StoreQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPaging<StoreDto>> result = new APIResult<APIPaging<StoreDto>>();
            result.Code = APIEnums.ok;

            try
            {
                // 获取所有未删除的仓库数据
                var query = storeRepository.GetAll()
                    .AsNoTracking()
                    .Where(x => !x.IsDelete);

                // 转换为DTO
                var storeQuery = query.Select(store => new StoreDto
                {
                    Id = store.Id,
                    StoreName = store.StoreName,
                    CreateUserId = store.CreateUserId,
                    CreateTime = store.CreateTime,
                    UpdateUserId = store.UpdateUserId,
                    UpdateTime = store.UpdateTime,
                    IsDelete = store.IsDelete
                });

                // 创建分页对象
                APIPaging<StoreDto> paging = new APIPaging<StoreDto>();
                paging.Count = storeQuery.Count();
                paging.List = storeQuery
                    .ToList();

                result.Data = paging;
                
                logger.LogInformation($"成功获取仓库列表，共{paging.Count}条记录");
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取仓库列表时发生错误");
                result.Code = APIEnums.fail;
                result.Message = "获取仓库列表失败";
            }

            return Task.FromResult(result);
        }
    }
}